<template>
    <div id='system-user'>
        <h1 class="card-title">
           <!--  <p><span>员工账号管理</span></p> -->
            <div class="card-title__button-box" v-if='allRoles.length'>
                <div class="form-item__value">
                    <select-group v-model='permissionSelect' @input='reGetList'>
                        <select-option value='' text='所有'></select-option>
                        <select-option v-for='item in allRoles' :key='item.roleCode' :value='item.roleCode' :text='item.roleName'></select-option>
                    </select-group>
                </div>
                <a class="card-title__button" @click='showNewUser'>新增员工账号</a>
            </div>
        </h1>
        <loading v-if='loading'></loading>
        <p class='no-data' v-if='!loading && !records.length'>暂无数据</p>
        <div class="table-list" v-if='!loading && records.length'>
            <table>
                <thead class="table-list__head">
                    <tr>
                        <th>账号</th>
                        <th>姓名</th>
                        <th>手机号</th>
                        <th>权限组</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody class='table-list__body have-border'>
                    <tr v-for='item in records'>
                        <td>{{ item.accName || placeholder }}</td>
                        <td>{{ item.name || placeholder }}</td>
                        <td>{{ item.phone || placeholder }}</td>
                        <td>
                            <div class='roles-list'>
                                <div class="tag__list"><p class='tag__item' v-for='roleItem in item.roles'>{{roleItem.roleName}} </p></div>
                            </div>
                        </td>
                        <td>{{ item.loginStatusStr || placeholder }}</td>
                        <td>
                            <div class='option-box'>
                                <span class='option-button' v-if='item.loginStatus == "FORBID"' @click='showUnLock(item.id)'>解锁</span>
                                <span class='option-button' v-if='item.loginStatus == "OK"' @click='showLock(item.id)'>锁定</span>
                                <span class='option-button' @click='showEditUser(item)'>编辑</span>
                                <span class='option-button' @click='showResetConfirm(item)'>重置密码</span>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
           <!--  <pagination
                :current-page='listInfo.pageNum'
                :total-page='listInfo.totalPage'
                @pageChange='getList'></pagination> -->
                 <el-pagination class="pan"  @current-change="handleCurrentChange" :current-page="listInfo.pageNum"  layout="total, prev, pager, next, jumper" 
                        :total="listInfo.totalCount" :background="true">
                </el-pagination>
        </div>


        <confirm
            :show='show_confirm_lock'
            title='确认锁定账户'
            :loading='loading_lock'
            @close='show_confirm_lock=false'
            @confirm='lock'>
        </confirm>

        <confirm
            :show='show_confirm_unLock'
            title='确认解锁账户'
            :loading='loading_unLock'
            @close='show_confirm_unLock=false'
            @confirm='unLock'>
        </confirm>

        <confirm
            :show='show_confirm_reset'
            title='确认重置密码'
            :loading='loading_reset'
            @close='show_confirm_reset=false'
            @confirm='resetPwd'>
        </confirm>

        <modal 
            title='编辑员工账号'
            :show='show_modal_user' 
            :loading='loading_save' 
            @close='show_modal_user=false'
            @confirm='saveUser'>
            <div class="modal-add-account__main">
                <div class="modal-form-wrap">
                    <ul class='modal-form'>
                        <li class='form-item'>
                            <span class="form-item__key">账号</span>
                            <div class="form-item__value">
                                <input type="text" placeholder="请输入账号" v-model='curItem.accName'>
                            </div>
                        </li>
                        <!-- <li class='form-item'>
                            <span class="form-item__key">初始密码</span>
                            <div class="form-item__value">
                                <input type="password" placeholder="请输入初始密码" v-model='accName'>
                            </div>
                        </li>
                        <li class='form-item'>
                            <span class="form-item__key">确认初始密码</span>
                            <div class="form-item__value">
                                <input type="password" placeholder="请再次输入初始密码" v-model='accName'>
                            </div>
                        </li> -->
                        <li class='form-item'>
                            <span class="form-item__key">姓名</span>
                            <div class="form-item__value">
                                <input type="text" placeholder="请输入姓名" v-model='curItem.name'>
                            </div>
                        </li>
                        <li class='form-item'>
                            <span class="form-item__key">手机号</span>
                            <div class="form-item__value">
                                <input type="text" placeholder="请输入手机号" v-model='curItem.phone'>
                            </div>
                        </li>
                        <li class='form-item'>
                            <span class="form-item__key">邮箱(选填)</span>
                            <div class="form-item__value">
                                <input type="text" placeholder="请输入邮箱" v-model='curItem.email'>
                            </div>
                        </li>
                        <li class='form-item'>
                            <span class="form-item__key">角色类型</span>
                            <div class="form-item__value">
                                <select-group v-model='curItem.roleType' @input='clearCurPermission'>
                                    <select-option  value='manager' text='管理角色'></select-option>
                                    <select-option  value='operator' text='操作角色'></select-option>
                                </select-group>
                            </div>
                        </li>
                        <li class='form-item' v-if='show_modal_user && curItem.roleType.value'>
                            <span class="form-item__key">权限组</span>
                            <div class="form-item__value">
                                <loading v-if='loading_roleList' mode='full'></loading>
                                <select-group 
                                    v-model='curItem.permission' 
                                    placeholder='请选择权限组（多选' 
                                    multiple
                                    fixed
                                    key='managerSelect'
                                    v-if='curItem.roleType.value == "manager"'>
                                    <select-option v-for='item in roleListManager' :value='item.roleCode' :text='item.roleName' :key='item.roleCode'></select-option>
                                </select-group>
                                <select-group 
                                    v-model='curItem.permission' 
                                    placeholder='请选择权限组（多选）' 
                                    multiple 
                                    key='operatorSelect'
                                    v-if='curItem.roleType.value == "operator"'>
                                    <select-option v-for='item in roleListOperator' :value='item.roleCode' :text='item.roleName' :key='item.roleCode'></select-option>
                                </select-group>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </modal>
    </div>
</template>

<script>
    import { Promise } from 'es6-promise'
    import selectGroup from '../components/SelectGroup.vue'
    import selectOption from '../components/SelectOption.vue'
    import datePicker from '../components/DatePicker.vue'
    import modal from '../components/Modal.vue'
    import confirm from '../components/Confirm.vue'
    import buttonLoading from '../components/ButtonLoading.vue'
    import pagination from '../components/Pagination.vue'
    import loading from '../components/Loading.vue'
    import tab from '../components/Tab.vue'
    import tabBox from '../components/TabBox.vue'
    import dateFormat from '../filters/filter-dateFormat'
    import echarts from '../components/Echarts.vue'
    import toYuan from '../filters/filter-toYuan'
    import  { mapGetters, mapActions }  from 'vuex'
    import { systemApi, allApi, youxinApi } from '../api/api'
    import { systemUserValidation } from '../validation/validation'
    import { rules } from '../utils/utils'
    import moment from 'moment'


    export default {
        components:{
            selectGroup,
            selectOption,
            echarts,
            loading,
            modal,
            tab,
            tabBox,
            confirm,
            buttonLoading,
            pagination,
            datePicker
        },
        filters:{
            dateFormat,
            toYuan,
            booleanToStr(boolean){
                if(boolean === true){
                    return '是'
                }
                else{
                    return '否'
                }
            }
        },
        data() {
            return {
                roleListManager:[],
                roleListOperator:[],
                show_modal_user:false,
                show_confirm_lock:false,
                show_confirm_reset:false,
                show_confirm_unLock:false,
                chartData:'',
                curItem:{
                    accName:'',
                    name:'',
                    phone:'',
                    email:'',
                    roleType:{
                        value:'',
                        text:'请选择角色类型'
                    },
                    permission:[]
                },
                data:'',
                name:'',
                accName:'',
                phone:'',
                curId:'',
                email:'',
                myChart:'',
                chartOptions:'',
                placeholder:'--',
                loading_chart:false,
                loading_reset:false,
                loading_lock:false,
                loading_unLock:false,
                loading_roleList:false,
                loading_save:false,
                show_reportDetail:false,
                recommend:0,
                modalTitle:'',
                roleType:{
                    value:'',
                    text:'请选择角色类型'
                },
                status:{
                    value:'',
                    text:'所有类型'
                },
                permission:[],
                permissionSelect:{
                    value:'',
                    text:'所有'
                },
                allRoles:[],
                trend:[],
                curDetail:{},
                curId:'',
                list:[],
                listInfo:{},
                records:[],
                date:'',
                dateFrom:'',
                dateTo:'',
                mobile:'',
                loading:true,
                loading_count:true,
            }
        },
        computed:{
            ...mapGetters([
                'msgTip',
                'localInfo'
            ]),
            currentPage(){
                if(_.isEmpty(this.listInfo)) return 1
                return this.listInfo.pageNum
            },
        },
        methods:{
            // actions
            ...mapActions([
                'showLoading',
                'hideLoading',
                'setMsgTip'
            ]),
             handleCurrentChange(val){
                console.log(`当前页: ${val}`);
                this.getList(val);
            },
            // filters
            timestampToDate(timestamp){
                if(!timestamp) return this.placeholder
                return moment(timestamp).format('YYYY-MM-DD')
            },

            // function
            clearCurPermission(){
                this.curItem.permission.splice(0)
            },
            getPermissionArr(){
                let text = ''
                if(this.curItem.permission){
                    _.each(this.curItem.permission,(value,index)=>{
                        if(text == ''){
                            text = `${value.value}`
                            console.log(`${value.value}`)
                            return
                        } 
                        text = `${text},${value.value}`
                        console.log(`${text},${value.value}`)
                    })
                }
                console.log(text)
                return text
            },
            resetCurItem(){
                this.curItem = {
                    accName:'',
                    name:'',
                    phone:'',
                    email:'',
                    roleType:{
                        value:'',
                        text:'请选择角色类型'
                    },
                    permission:[]
                }
            },
            showNewUser(){
                this.resetCurItem()
                this.show_modal_user = true
            },
            showEditUser(item){
                this.curItem = _.cloneDeep(item)
                this.curItem.permission = []
                _.each(this.curItem.roles,(value,index)=>{
                    this.curItem.permission.push({
                        value:value.roleCode,
                        text:value.roleName,
                    })
                })
                this.curItem.roleType={
                    value:this.curItem.roleType,
                    text:this.curItem.roleTypeStr,
                }
                // this.getRoleList()
                this.show_modal_user = true
            },
            showResetConfirm(item){
                this.show_confirm_reset = true
                this.curId = item.id
            },
            showModalDetail(item,title){
                let name 
                if(item){
                    name = item.appName
                }
                this.modalTitle = title
                this.getTrend(name)
                this.loading_chart - true
                this.show_reportDetail = true
            },
            saveUser(){
                let permissionArr = this.getPermissionArr()
                let params = {
                    id:this.curItem.id,
                    accName:this.curItem.accName,
                    name:this.curItem.name,
                    phone:this.curItem.phone,
                    email:this.curItem.email,
                    roleType:this.curItem.roleType.value,
                    roleCode:permissionArr,
                }
                if(!systemUserValidation(params)) return
                this.loading_save = true
                systemApi.saveOperator(params)
                .then(result=>{
                    this.loading_save = false
                    this.show_modal_user = false
                    this.getList(this.currentPage)
                })
                .catch(error => {
                    console.error(error)
                    this.loading_save = false
                })
            },
            showLock(id){
                this.show_confirm_lock = true
                this.curId = id
            },
            showUnLock(id){
                this.show_confirm_unLock = true
                this.curId = id
            },
            lock(){
                this.loading_lock = true
                systemApi.lockOperator({
                    id:this.curId
                })
                .then(result=>{
                    this.loading_lock = false
                    this.show_confirm_lock = false
                    this.getList(this.currentPage)
                })
                .catch(error => {
                    console.error(error)
                    this.loading_lock = false
                })
            },
            unLock(){
                this.loading_unLock = true
                systemApi.unLockOperator({
                    id:this.curId
                })
                .then(result=>{
                    this.loading_unLock = false
                    this.show_confirm_unLock = false
                    this.getList(this.currentPage)
                })
                .catch(error => {
                    console.error(error)
                    this.loading_unLock = false
                })
            },
            reGetList(){
                this.getList(1)
            },
            getList(num = 1){
                this.loading = true
                systemApi.operatorList({
                    pageSize:10,
                    pageIndex:num,
                    role:this.permissionSelect.value
                })
                .then(result=>{
                    this.loading = false
                    this.listInfo = result
                    this.records = result.records
                    if(result.totalPage < result.pageNum){
                        this.getList(result.totalPage)
                    }
                })
                .catch(error => {
                    console.error(error)
                    this.loading = false
                })
            },
            getRoleList(type){
                this.loading_roleList = true
                systemApi.roleList({
                    roleType:type
                })
                .then(result=>{
                    this.loading_roleList = false
                    if(type == 'manager'){ this.roleListManager = result }
                    if(type == 'operator'){ this.roleListOperator = result }
                })
                .catch(error => {
                    this.loading_roleList = false
                    console.error(error)
                })
            },
            getAllRoles(){
                systemApi.allRoles()
                .then(result=>{
                    this.allRoles = result
                })
                .catch(error => {
                    console.error(error)
                })
            },
            resetPwd(appName){
                this.loading_reset = true
                systemApi.resetOperatorPwd({
                    id:this.curId
                })   
                .then(result=>{
                    this.loading_reset = false
                    this.show_confirm_reset = false
                })
                .catch(error => {
                    console.error(error)
                    this.loading_reset = false
                })
            },
            setDays(index){
                let days
                if(index === 0) days = 7
                else if(index === 1) days = 30
                else if(index === 2) days = 60

                this.chartOptions.dataZoom = [{
                    startValue: moment().subtract(days, 'days').format('YYYY-MM-DD')
                }, {
                    type: 'inside'
                }]
            },
        },
        created(){
            this.getList()
            this.getAllRoles()
            this.getRoleList('manager')
            this.getRoleList('operator')
            // this.getTrend()
        }
    }
</script>

<style lang="scss">
    @import "../sass/variables";
    @import "../sass/extends";
    @import "../sass/mixins";

    #report-index{
        padding:0 40px 20px 40px;
        box-sizing:border-box;
        overflow:auto;
        .loading-min-height{
            min-height:300px;
        }
        .user-data{
            padding-bottom: 20px;
        }
        .user-data__list{
            display:flex;
            padding-top: 20px;
            min-height:140px;
        }
        .user-data__item{
            display:flex;
            flex-direction: column;
            justify-content:center;
            align-items:center;
            width: 200px;
            height:120px;
            border:1px solid $sectionColor;
            border-radius:4px;
            box-shadow:rgba(0, 0, 0, 0.03) 0px 1px 6px, rgba(0, 0, 0, 0.04) 0px 1px 4px;
            margin-right:20px;
            span{
                display: block;
                font-size: 30px;
                color:$green;
            }
            p{
                padding-top: 10px;
            }
        }
    }
</style>
